package avicit.im.lantop.basic.reportmanager.service.impl;

import avicit.im.lantop.basic.reportmanager.domain.*;
import avicit.im.lantop.basic.reportmanager.service.ReportManagerServices;
import avicit.platform6.api.syslookup.SysLookupAPI;
import avicit.platform6.api.syslookup.impl.SysLookupAPImpl;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.PojoUtil;
import avicit.platform6.commons.utils.web.TreeNode;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.dao.Paging;
import avicit.platform6.core.dao.PropertyFilter;
import avicit.platform6.core.dao.PropertyFilter.MatchType;
import avicit.platform6.core.dao.hibernate.CommonHibernateDao2;
import avicit.platform6.core.domain.BeanBase;
import avicit.platform6.core.exception.DaoException;
import avicit.platform6.core.jdbc.JdbcAvicit;
import avicit.platform6.core.properties.PlatformConstant.OpResult;
import avicit.platform6.core.properties.PlatformConstant.OpType;
import avicit.platform6.api.session.SessionHelper;
import avicit.platform6.core.spring.SpringFactory;
import avicit.platform6.modules.system.syslog.service.LogBaseFactory;
import avicit.platform6.modules.system.syslog.service.SysLogUtil;
import com.github.pagehelper.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 金航数码科技有限责任公司
 * </p>
 * <p>
 * 作者：张欢欢
 * </p>
 * <p>
 * 邮箱：xtcqw369@163.com
 * </p>
 * <p>
 * 创建时间： 2015-11-3 下午1:58:24
 * </p>
 * <p>
 * 类说明：报表管理实现类
 * </p>
 * <p>
 * 修改记录：
 * </p>
 */
@Service
@SuppressWarnings({"unchecked", "null" })
public class ReportManagerServicesImpl implements ReportManagerServices {

    @Autowired(required = true)
    private JdbcAvicit jdbcAvicit;

    @Autowired(required = true)
    private CommonHibernateDao2 hibernateDao;

    private final Logger logger = LoggerFactory.getLogger(ReportManagerServicesImpl.class);

    SysLookupAPI upLoader = SpringFactory.getBean(SysLookupAPImpl.class); // 加载通用代码对象

    /**
     * TODO 递归查询树结构
     * @param id		根ID
     * @param level			层级
     * @param orgId 	组织ID
     * @param orgIdentity 	组织应用Id
     * @param contextPath	上下文路径，用于存储报表模板
     * @param
     * @return
     * @throws
     */
    @Override
    public List<TreeNode> getTreeExerciseByParentId(String parentId, String orgId, String orgIdentity, int level, String contextPath) {
        List<TreeNode> node = new ArrayList<TreeNode>();
        if (level == 0) {
            return null;
        }
        if (level != -1) {
            level--;
        }

        //根据组织ID 获得 组织信息
        Map<String,Object> orgInfo = getOrgInfoById(orgIdentity);

        List<Map<String, Object>> subTrees = this.getTreeExerciseByParentId(parentId,orgId);
        for (Map<String, Object> subtree : subTrees) {
            TreeNode treeNode = new TreeNode();
            String id = (String) subtree.get("ID");
            String fatherId = (String) subtree.get("PARENT_ID");
            String name = (String) subtree.get("REPORT_NAME");
            if(parentId.equals("-1")){
                name = orgInfo.get("TEMP_NAME").toString();
            }
            treeNode.set_parentId(fatherId);
            treeNode.setId(id);
            treeNode.setText(name);
            BigDecimal count = BigDecimal.valueOf(Long.valueOf(subtree.get("CHILDCOUNT") + ""));
            int s = Integer.valueOf(count.toString());
            String cptFileName = (String) subtree.get("ATTRIBUTE_01");
            HashMap<String, Object> attr = new HashMap<String, Object>();
            attr.put("count", count);
            attr.put("cptFileName", cptFileName);
            // 在这里判断模板文件是否存在，如果不存在，则添加属性，用于在模板导出的时候
            String filePath = contextPath + File.separator + "reportlets" + File.separator + cptFileName;
            attr.put("testPath", filePath);
            File file = new File(filePath);
            if (file.exists()) {
                attr.put("cptFileExist", true);
            } else {
                attr.put("cptFileExist", false);
            }
            // 获取节点的类型
            String idType = (String) subtree.get("REPORT_TYPE");
            if ("0".equals(idType)) {
                // 表示是分类信息
                treeNode.setIconCls("icon-im-newnmodulefile");
            } else {
                // 如果是模板信息，则需要额外的查询下该模板是否已经进行了数据源配置
                List<?> lrfList = getListByColumnValue(LantopReportField.class, "reportId", id);
                if (lrfList.size() == 0) {
                    // 没有配置过字段信息
                    attr.put("hasField", false);
                } else {
                    attr.put("hasField", true);
                    String fields = "";
                    for (Object obj : lrfList) {
                        LantopReportField lrf = (LantopReportField) obj;
                        fields = fields + lrf.getFieldChinese() + ",";
                    }
                    // 去掉最后一个,
                    fields = fields.substring(0, fields.length() - 1);
                    attr.put("fields", fields);
                    // 查询 LantopReportSetField 表中有关表信息
                    List<?> lrsfList = getListByColumnValue(LantopReportSetField.class, "reportId", id);
                    if (lrsfList.isEmpty() == false) {
                        String selectTableNames = "";
                        for (int i = 0; i < lrsfList.size(); i++) {
                            LantopReportSetField lrsf = (LantopReportSetField) lrsfList.get(i);
                            String tableName = lrsf.getTableName();
                            if (tableName == null || selectTableNames.contains(tableName)) {
                                continue;
                            }
                            selectTableNames = selectTableNames + lrsf.getTableName() + ",";
                        }
                        selectTableNames = selectTableNames.substring(0, selectTableNames.length() - 1);
                        attr.put("resultDataSource", selectTableNames);
                    }
                }
            }
            attr.put("reportType", idType);
            treeNode.setAttributes(attr);
            if (s > 0) {
                if (level > 0) {
                    treeNode.setState("open");
                } else {
                    treeNode.setState("open");
                }
                treeNode.setChildren(getTreeExerciseByParentId(id,orgId,orgIdentity, level, contextPath));
            } else {
                treeNode.setState("open");
            }
            node.add(treeNode);
        }
        return node;
    }

    /**
     * TODO 获取已保存的报表节点树行结构
     *
     * @param parentId
     * @param orgId
     * @return List<Map<String,Object>>
     * @throws
     */
    private List<Map<String, Object>> getTreeExerciseByParentId(String parentId,String orgId) {
        StringBuffer sql = new StringBuffer();

        sql.append(" SELECT (SELECT COUNT(1) " + "  FROM LANTOP_REPORT_BASETABLE t2 " + "  WHERE t2.PARENT_ID = t.id) childCount, " + "  t.* " + "  FROM LANTOP_REPORT_BASETABLE t " + "  WHERE t.PARENT_ID = '" + parentId + "'");
        sql.append(" AND t.ORG_ID = '"+orgId+"'");

        return jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
    }

    @Override
    public String insertIntoLantopReportTreeForUpload(Map<String, String> paramsMap) {

        String sysId = paramsMap.get("sysId");
        String reportName = paramsMap.get("reportName");
        String parentId = paramsMap.get("parentId");

        LantopReportBasetable lrb = new LantopReportBasetable();
        lrb.setId(ComUtil.getId());
        lrb.setParentId(parentId);
        lrb.setReportType("1");

        lrb.setReportName(reportName);
        lrb.setOrgId(ThreadContextHelper.getOrgId());
        lrb.setDeptId(ThreadContextHelper.getDeptId());
        lrb.setSysId(sysId);
        lrb.setSysApplicationId(SessionHelper.getApplicationId());
        lrb.setAttribute01(reportName + ".cpt");

        PojoUtil.setSysProperties(lrb, OpType.insert);
        try {
            hibernateDao.save(lrb);
            SysLogUtil.log(lrb, null, OpType.insert, OpResult.success);
        } catch (Exception e) {
            logger.debug("save error, ", e);

        }

        return lrb.getId();
    }

    @Override
    public boolean saveLantopReport(Map<String, Object> paramsMap) {
        boolean success = false;
        String sysId = (String) paramsMap.get("sysId");
        String templateId = (String) paramsMap.get("templateId");
        String outputFields = (String) paramsMap.get("outputFields"); // 应输出字段

        List<Map<String, String>> currFields = (List<Map<String, String>>) paramsMap.get("currFields"); // 实际输出字段
        List<String> tableNamesList = (List<String>) paramsMap.get("tableNames");
        String tableNames = "";
        for (String table : tableNamesList) {
            if(table == null || table.equals("") ||table.equals("null")){
                continue;
            }
            tableNames = tableNames + table + ",";
        }
        if (!"".equals(tableNames)) {
            tableNames = tableNames.substring(0, tableNames.length() - 1);
        }

        // 创建 LantopReportDatasource, 保存于模板对应的数据表, 一个模板可能对应多个物理表
        // List<LantopReportDatasource> lrdList =
        // createLantopReportDatasourceObject(sysId, templateId,
        // tableNamesList);

        // for (int i = 0; i < tableNamesList.size(); i++) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sysId", sysId);
        map.put("reportId", templateId);

        // 根据参数检查在数据库重是否存在报表配置项，如果有则删除
        if (tableNamesList.size() > 1) {
            // 两张表
            map.put("attribute01", tableNames);
            map.put("tableName", null);
        } else {
            map.put("attribute01", null);
            map.put("tableName", tableNamesList.get(0));
        }
        List<Map<String, Object>> resultList = checkExistsByReportIdAndReportName(map);
        if (null != resultList) {
            try {
                for (Map<String, Object> resultMap : resultList) {
                    String id = (String) resultMap.get("ID");
                    LantopReportSetField lantopReportSetField = (LantopReportSetField) getObjectById(LantopReportSetField.class, id);
                    hibernateDao.delete(lantopReportSetField);
                    SysLogUtil.log(lantopReportSetField, null, OpType.insert, OpResult.success);
                }
            } catch (Exception e) {
                logger.error("delete fail, ", e);
            }
        }
        // }

        // 创建 LantopReportField, 保存模板应输出字段
        // 这里对于导入的模板需要特殊处理，导入的模板需要将字段信息存入到lantopReportField表中
        // 用户自定义数据源， 或者是数据表数据源不需要在存入到lantopreportField表中，否则会出现问题
        // List<LantopReportField> lrfList =
        // createLantopReportFieldObject(sysId, templateId, outputFields);
        // 检查在LantopReportField中是否有配置的字段,如果没有在加入, 如果有则不做任何操作
        List<?> lrfList = getListByColumnValue(LantopReportField.class, "reportId", templateId);
        if (lrfList.size() == 0) {
            if (null != outputFields || !"".equals(outputFields)) {
                // 利用output字段写入LantopReportField 字段值
                List<LantopReportField> lrfList1 = createLantopReportFieldObject(sysId, templateId, outputFields);
                for (LantopReportField lrf : lrfList1) {
                    hibernateDao.save(lrf);
                    SysLogUtil.log(lrf, null, OpType.insert, OpResult.success);
                }
            }
        }

        // 创建 LantopReportSetField , 保存模板实际输出字段
        List<LantopReportSetField> lrsfList = createLantopReportSetFieldObject(sysId, templateId, currFields,tableNamesList);
        try {
            if (tableNamesList.size() > 1) {
                // 如果是两张表，则额外的插入attribute01字段
                for (int i = 0; i < lrsfList.size(); i++) {
                    lrsfList.get(i).setAttribute01(tableNames);
                }

            }
            for (int i = 0; i < lrsfList.size(); i++) {
                hibernateDao.save(lrsfList.get(i));
                SysLogUtil.log(lrsfList.get(i), null, OpType.insert, OpResult.success);
            }

            success = true;
        } catch (Exception e) {
            logger.error("error: ", e);
            success = false;
        }

        return success;
    }

    /**
     * TODO 根据模板ID生成一个 LantopReportDatasource 对象
     *
     * @param sysId
     *            系统Id
     * @param templateId
     *            模板ID
     * @param tableNamesList
     *            表名集合
     * @return List<LantopReportDatasource>
     * @throws
     */
    private List<LantopReportDatasource> createLantopReportDatasourceObject(String sysId, String templateId, List<String> tableNamesList) {
        List<LantopReportDatasource> list = new ArrayList<LantopReportDatasource>();
        LantopReportDatasource lantopReportDatasource = new LantopReportDatasource();
        lantopReportDatasource.setId(ComUtil.getId()); // 生成UUID
        lantopReportDatasource.setSysId(sysId);
        lantopReportDatasource.setReportId(templateId); // 设置报表模板ID
        lantopReportDatasource.setOrgId(SessionHelper.getCurrentOrgId());
        lantopReportDatasource.setDeptId(SessionHelper.getCurrentDeptId());
        lantopReportDatasource.setSysApplicationId(SessionHelper.getApplicationId());
        PojoUtil.setSysProperties(lantopReportDatasource, OpType.insert); // 设置公共属性
        String tableName = "";
        for (String strName : tableNamesList) {
            tableName = tableName + strName + ",";

        }
        tableName = tableName.substring(0, tableName.length() - 1);
        lantopReportDatasource.setSourceTable(tableName); // 设置与模板管理的物理表表
        list.add(lantopReportDatasource);

        return list;
    }

    /**
     * TODO 根据模板ID生成一个 LantopReportField 对象, 这里存储应输出字段
     *
     * @param sysId
     *            系统ID
     * @param templateId
     *            模板ID
     * @param outputFields
     *            应输出字段
     * @return List<LantopReportField>
     * @throws
     */
    private List<LantopReportField> createLantopReportFieldObject(String sysId, String templateId, String outputFields) {

        List<LantopReportField> list = new ArrayList<LantopReportField>();
        // 设置应输出字段信息
        String[] fields = outputFields.split(",");
        int index = 0;
        for (String field : fields) {

            LantopReportField lantopReportField = new LantopReportField();
            lantopReportField.setId(ComUtil.getId()); // 生成UUID
            lantopReportField.setFieldChinese(field);
            lantopReportField.setFieldSerial(new BigDecimal(index)); // 设置字段顺序

            lantopReportField.setSysId(sysId);
            lantopReportField.setReportId(templateId); // 设置报表模板ID
            lantopReportField.setOrgId(SessionHelper.getCurrentOrgId());
            lantopReportField.setDeptId(SessionHelper.getCurrentDeptId());
            lantopReportField.setSysApplicationId(SessionHelper.getApplicationId());
            PojoUtil.setSysProperties(lantopReportField, OpType.insert); // 设置公共属性
            index++;

            list.add(lantopReportField);

        }

        return list;
    }

    /**
     * TODO 生成一个 LANTOP_REPORT_BASETABLE 对象
     *
     * @param paramsMap
     *            属性集合
     * @return LantopReportBasetable
     * @throws
     */
    private LantopReportBasetable createLantopReportBasetableObject(Map<String, Object> paramsMap) {
        String sysId = (String) paramsMap.get("sysId");
        String id = (String) paramsMap.get("id");
        String parentId = (String) paramsMap.get("_parentId");
        String reportName = (String) paramsMap.get("text");
        String reportType = (String) paramsMap.get("reportType");

        LantopReportBasetable lrb = new LantopReportBasetable();

        if ("".equals(id)) {
            //
            lrb.setId(ComUtil.getId());
            PojoUtil.setSysProperties(lrb, OpType.insert);
            lrb.setSysId(sysId);
            lrb.setParentId(parentId);
            lrb.setReportName(reportName);
            lrb.setReportType(reportType);
            lrb.setOrgId(SessionHelper.getCurrentOrgId());
            lrb.setDeptId(SessionHelper.getCurrentDeptId());
            lrb.setSysApplicationId(SessionHelper.getApplicationId());

            // 目前认为节点名称和模板名称一致
            if ("1".equals(reportType)) {
                // 则在 Attribute01 存入模板名称
                lrb.setAttribute01(reportName + ".cpt");

            }

        } else {
            lrb = (LantopReportBasetable) getObjectById(LantopReportBasetable.class, id);
            if (null != lrb) {
                lrb.setReportName(reportName);

                // 目前认为节点名称和模板名称一致
                if ("1".equals(reportType)) {
                    // 则在 Attribute01 存入模板名称
                    lrb.setAttribute01(reportName + ".cpt");

                }

                PojoUtil.setSysProperties(lrb, OpType.update);

            }

        }

        return lrb;

    }

    /**
     * TODO 根据模板ID生成一个 LantopReportField 对象, 这里存储实际输出字段
     *
     * @param sysId
     *            系统ID
     * @param templateId
     *            模板ID
     * @param fieldsList
     *            字段集合
     * @return List<LantopReportSetField>
     * @throws
     */
    private List<LantopReportSetField> createLantopReportSetFieldObject(String sysId, String templateId, List<Map<String, String>> fieldsList,List<String> tableNamesList) {

        List<LantopReportSetField> list = new ArrayList<LantopReportSetField>();
        int index = 0;
        String name = null;
        if(tableNamesList.size()==1){
            name = tableNamesList.get(0);
        }
        for (Map<String, String> map : fieldsList) {
            String fieldChinese = map.get("COL_LABEL");
            String fieldEnglish = map.get("COL_NAME");
            String tableName = "";
            if(null != map.get("TABLE_NAME") && !map.get("TABLE_NAME").equals("")){
                tableName = map.get("TABLE_NAME");
            }else{
                tableName= name;
            }

            LantopReportSetField lantopReportSetField = new LantopReportSetField();

            lantopReportSetField.setId(ComUtil.getId()); // 生成UUID
            lantopReportSetField.setFieldChinese(fieldChinese); // 字段中文名称
            lantopReportSetField.setFieldEnglish(fieldEnglish); // 字段英文名称
            lantopReportSetField.setFieldSerial(new BigDecimal(index)); // 字段顺序
            lantopReportSetField.setTableName(tableName); // 表名称
            lantopReportSetField.setSysId(sysId);
            lantopReportSetField.setReportId(templateId); // 设置报表模板ID
            lantopReportSetField.setOrgId(SessionHelper.getCurrentOrgId());
            lantopReportSetField.setDeptId(SessionHelper.getCurrentDeptId());
            lantopReportSetField.setSysApplicationId(SessionHelper.getApplicationId());

            index++;
            PojoUtil.setSysProperties(lantopReportSetField, OpType.insert); // 设置公共属性

            list.add(lantopReportSetField);

        }

        return list;
    }

    @Override
    public boolean insertIntoLantopReportTree(Map<String, Object> paramsMap) {
        boolean success = false;
        LantopReportBasetable lrb = new LantopReportBasetable();
        String sysId = (String) paramsMap.get("sysId");
        String id = (String) paramsMap.get("id");
        String parentId = (String) paramsMap.get("_parentId");
        String reportName = (String) paramsMap.get("text");
        String reportType = (String) paramsMap.get("reportType");
        if ("".equals(id)) {
            // 新增
            lrb.setId(ComUtil.getId());
            PojoUtil.setSysProperties(lrb, OpType.insert);
            lrb.setSysId(sysId);
            lrb.setParentId(parentId);
            lrb.setReportName(reportName);
            lrb.setReportType(reportType);
            lrb.setOrgId(ThreadContextHelper.getOrgId());
            lrb.setDeptId(ThreadContextHelper.getDeptId());
            lrb.setSysApplicationId(SessionHelper.getApplicationId());
            SysLogUtil.log(lrb, null, OpType.insert, OpResult.success);
        } else {
            // 首先根据Id查找
            // 删除之前, 首先根据ID查找
            LantopReportBasetable oldBean = (LantopReportBasetable) getObjectById(LantopReportBasetable.class, id);
            if (null != lrb) {
                this.hibernateDao.evict(oldBean);
                PojoUtil.copyProperties(lrb, oldBean, true);
                lrb.setReportName(reportName);
                SysLogUtil.log(lrb, oldBean, OpType.update, OpResult.success);
                PojoUtil.setSysProperties(lrb, OpType.update);
            }
        }
        try {
            hibernateDao.saveOrUpdate(lrb);
            success = true;
        } catch (Exception e) {
            logger.error("save to LantopReportBasetable error, ", e);
            success = false;
        }
        return success;
    }

    @Override
    public boolean deleteLantopReportTree(Map<String, Object> paramsMap) {

        boolean success = true;
        String ids = (String) paramsMap.get("id");
        // 拆分 id ， 循环删除
        String[] idss = ids.split(",");
        for (String id : idss) {
            if (!"".equals(id)) {
                // 删除之前, 首先根据ID查找
                // 需要额外的删除其他的配置信息LanTop_Report_DataSource,
                // LanTop_Report_Field,LanTop_Report_Set_Field
                LantopReportBasetable lrb = (LantopReportBasetable) getObjectById(LantopReportBasetable.class, id);
                if (null != lrb) {
                    try {

                        // 删除 LantopReportDatasource
                        List<?> list = (List<?>) getListByColumnValue(LantopReportDatasource.class, "reportId", id);
                        hibernateDao.deleteAll(list);
                        SysLogUtil.log("报表管理模块", "删除记录", OpType.delete, OpResult.success, LogBaseFactory.getLogBase());
                        // 删除 LantopReportField
                        list = (List<?>) getListByColumnValue(LantopReportField.class, "reportId", id);
                        hibernateDao.deleteAll(list);
                        SysLogUtil.log("报表管理模块", "删除记录", OpType.delete, OpResult.success, LogBaseFactory.getLogBase());
                        // 删除 LantopReportSetField
                        list = (List<?>) getListByColumnValue(LantopReportSetField.class, "reportId", id);
                        hibernateDao.deleteAll(list);
                        SysLogUtil.log("报表管理模块", "删除记录", OpType.delete, OpResult.success, LogBaseFactory.getLogBase());

                        hibernateDao.delete(lrb);
                        SysLogUtil.log(lrb, null, OpType.delete, OpResult.success);
                    } catch (Exception e) {
                        success = false;
                        logger.error("delete LantopReportBasetable id :" + id + " error.");
                    }
                } else {
                    logger.error("not find LantopReportBasetable id :" + id + " error.");
                }

            }

        }

        return success;
    }

    /**
     * 根据ID查找对象
     *
     */
    private Object getObjectById(Class<?> c, String id) {

        return hibernateDao.getSession().get(c, id);

    }

    @Override
    public boolean saveUseCustomDataSource(Map<String, Object> paramsMap) {

        // 需要插入两张表的数据
        boolean success = true;

        // LANTOP_REPORT_BASETABLE
        LantopReportBasetable lrb = createLantopReportBasetableObject(paramsMap);
        hibernateDao.saveOrUpdate(lrb);

        String reportId = lrb.getId();

        String sysId = (String) paramsMap.get("sysId");

        // 取出用户设置的字段信息
        List<Map<String, String>> insertList = (List<Map<String, String>>) paramsMap.get("insertData");

        // 取出用户设置的字段信息
        List<Map<String, String>> updateList = (List<Map<String, String>>) paramsMap.get("updateData");

        // int index = 0;
        // 这里需要额外的查询下 字段顺序的最大值
        BigDecimal index = findMaxFieldSerialByReportId(reportId, sysId);
        if (null == index) {
            index = new BigDecimal("0");
        }

        for (Map<String, String> map : insertList) {

            LantopReportField lrf = new LantopReportField();
            lrf.setId(ComUtil.getId());

            lrf.setReportId(reportId);
            lrf.setFieldChinese(map.get("COL_LABEL"));
            lrf.setFieldEnglish(map.get("COL_NAME"));
            lrf.setFieldType(map.get("COL_TYPE"));
            lrf.setFieldContentLen(new BigDecimal(map.get("COL_LENGTH")));
            lrf.setFieldSerial(index);

            lrf.setSysId(sysId);
            lrf.setOrgId(SessionHelper.getCurrentOrgId());
            lrf.setDeptId(SessionHelper.getCurrentDeptId());

            PojoUtil.setSysProperties(lrf, OpType.insert);
            hibernateDao.save(lrf);
            SysLogUtil.log(lrf, null, OpType.insert, OpResult.success);
            index.add(new BigDecimal("1"));

        }

        for (Map<String, String> map : updateList) {
            LantopReportField lrf = (LantopReportField) getObjectById(LantopReportField.class, map.get("ID"));
            this.hibernateDao.evict(lrf);
            LantopReportField newBean = new LantopReportField();
            PojoUtil.copyProperties(newBean, lrf, true);
            newBean.setFieldChinese(map.get("COL_LABEL"));
            newBean.setFieldEnglish(map.get("COL_NAME"));
            newBean.setFieldType(map.get("COL_TYPE"));
            newBean.setFieldContentLen(new BigDecimal(map.get("COL_LENGTH")));
            SysLogUtil.log(newBean, lrf, OpType.update, OpResult.success);
            PojoUtil.setSysProperties(lrf, OpType.update);
            hibernateDao.update(lrf);

        }

        // 利用map带出一个参数
        paramsMap.put("___templateId", reportId);

        return success;
    }

    @Override
    public void findFieldInfosByReportid(Map<String, Object> paramsMap, Page<Map<String, Object>> page) {
        String sysId = (String) paramsMap.get("sysId");
        String reportId = (String) paramsMap.get("reportId");

        StringBuffer sql = new StringBuffer();
        sql.append("SELECT t.id AS ID, t.Field_Chinese AS COLLABEL, t.Field_English AS COLNAME, t.Field_Type AS COLTYPE, " + "   t.Field_Content_Len AS COLLENGTH, t.Tabsequence AS COLDECIMAL " + "   FROM LANTOP_REPORT_FIELD t " + "   where 1 =1 ");
        if (null != sysId) {
            sql.append(" AND t.Sys_Id='" + sysId + "'");
        }
        if (null != reportId) {
            sql.append(" AND t.Report_Id='" + reportId + "'");
        }

        sql.append(" ORDER BY t.Field_Serial ");

        Map<String, String> resultMap = new HashMap<String, String>();
        jdbcAvicit.pageForMap(page, sql.toString(), resultMap);
    }

    /**
     * TODO 根据模板ID，查找最大的序列ID
     *
     * @param reportId
     * @param sysId
     * @return BigDecimal
     * @throws
     */
    private BigDecimal findMaxFieldSerialByReportId(String reportId, String sysId) {

        BigDecimal big = null;

        StringBuffer sql = new StringBuffer();

        sql.append("SELECT t.Field_Serial AS serial " + "   FROM LANTOP_REPORT_FIELD t " + "   WHERE 1 = 1");
        if (null != sysId) {
            sql.append(" AND t.Sys_Id = '" + sysId + "'");
        }
        if (null != reportId) {
            sql.append(" AND t.Report_Id = '" + reportId + "'");
        }

        sql.append(" ORDER BY t.Field_Serial DESC ");

        List<Map<String, Object>> list = jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
        if (list.size() > 0) {
            big = new BigDecimal(list.get(0).get("SERIAL").toString());
        } else {
            return null;
        }

        return big.add(new BigDecimal("1"));
    }

//    @Override
//    public void findFieldInfosByReportid(Map<String, Object> paramsMap, Page<Map<String, Object>> page) {
//        String sysId = (String) paramsMap.get("sysId");
//        String reportId = (String) paramsMap.get("reportId");
//
//        StringBuffer sql = new StringBuffer();
//        sql.append("SELECT t.id AS ID, t.Field_Chinese AS COLLABEL, t.Field_English AS COLNAME, t.Field_Type AS COLTYPE, " + "   t.Field_Content_Len AS COLLENGTH, t.Tabsequence AS COLDECIMAL " + "   FROM LANTOP_REPORT_FIELD t " + "   where 1 =1 ");
//        if (null != sysId) {
//            sql.append(" AND t.Sys_Id='" + sysId + "'");
//        }
//        if (null != reportId) {
//            sql.append(" AND t.Report_Id='" + reportId + "'");
//        }
//
//        sql.append(" ORDER BY t.Field_Serial ");
//
//        Map<String, String> resultMap = new HashMap<String, String>();
//        jdbcAvicit.pageForMap(page, sql.toString(), resultMap);
//
//    }

    @Override
    public boolean deleteFieldInfosById(Map<String, Object> paramsMap) {
        boolean success = true;

        String ids = (String) paramsMap.get("ids");
        String[] idss = ids.split(",");
        for (String id : idss) {
            // 先查找, 然后删除
            LantopReportField lrf = (LantopReportField) getObjectById(LantopReportField.class, id);
            if (null != lrf) {
                try {
                    hibernateDao.delete(lrf);
                    SysLogUtil.log(lrf, null, OpType.delete, OpResult.success);
                } catch (Exception e) {
                    success = false;
                    logger.error("delete error LantopReportField id : " + id, e);
                }

            }

        }

        return success;
    }

    /**
     * 根据某一字段查询对象
     *
     */
    public List<?> getListByColumnValue(Class<?> c, String column, String value) {
        return hibernateDao.findBy(c, column, value, MatchType.EQ);

    }

    @Override
    public boolean saveDataBaseConfigForTable(Map<String, Object> paramsMap) {

        String sysId = (String) paramsMap.get("sysId");

        List<String> tableNamesList = (List<String>) paramsMap.get("tableNames");
        List<Map<String, String>> relationList = (List<Map<String, String>>) paramsMap.get("relation");
        List<Map<String, String>> sortList = (List<Map<String, String>>) paramsMap.get("sort");
        List<Map<String, String>> fieldInfos = (List<Map<String, String>>) paramsMap.get("fieldInfos");

        boolean success = true;

        try {
            // 插入或更新 LantopReportBaseTable
            LantopReportBasetable lrbt = createLantopReportBasetableObject(paramsMap);
            hibernateDao.saveOrUpdate(lrbt);
            String id = lrbt.getId();

            // LantopReportDatasource lrd = (LantopReportDatasource)
            // getObjectById(LantopReportDatasource.class, id);

            List<LantopReportDatasource> lrdListAll = (List<LantopReportDatasource>) getListByColumnValue(LantopReportDatasource.class, "reportId", id);
            if (lrdListAll.size() > 0) {
                hibernateDao.deleteAll(lrdListAll);
                SysLogUtil.log("报表管理模块", "删除记录", OpType.delete, OpResult.success, LogBaseFactory.getLogBase());
            }

            // 新增 LanTop_Report_DataSource
            List<LantopReportDatasource> lrdList = createLantopReportDatasourceObject(sysId, id, tableNamesList);
            for (LantopReportDatasource lrd1 : lrdList) {
                String rel = "";
                for (Map<String, String> relation : relationList) {
                    rel = rel + relation.get("COLNAME") + relation.get("OPRATION") + relation.get("COLNAME1") + ",";

                }
                if (!"".equals(rel)) {
                    rel = rel.substring(0, rel.length() - 1);
                }

                lrd1.setConditionExpression(rel);
                String sort1 = "";
                for (Map<String, String> sort : sortList) {
                    sort1 = sort1 + sort.get("COLNAME3") + "  " + sort.get("SORT") + ",";

                }
                if (!"".equals(sort1)) {
                    sort1 = sort1.substring(0, sort1.length() - 1);
                }

                lrd1.setSortExpression(sort1);
            }

            for (LantopReportDatasource lrd1 : lrdList) {
                hibernateDao.save(lrd1);
                SysLogUtil.log(lrd1, null, OpType.insert, OpResult.success);
            }

            List<LantopReportSetField> lrsListAll = (List<LantopReportSetField>) getListByColumnValue(LantopReportSetField.class, "reportId", id);
            if (lrsListAll.size() > 0) {
                hibernateDao.deleteAll(lrdListAll);
                SysLogUtil.log("表报管理模块", "删除记录", OpType.delete, OpResult.success, LogBaseFactory.getLogBase());
            }

            // 新增 LanTop_Report_Set_Field
            List<LantopReportSetField> lrsfList = createLantopReportSetFieldObject(sysId, id, fieldInfos,tableNamesList);
            String outputFields = "";
            for (LantopReportSetField lrsf : lrsfList) {
                outputFields = outputFields + lrsf.getFieldChinese() + ",";
                hibernateDao.save(lrsf);
                SysLogUtil.log(lrsf, null, OpType.insert, OpResult.success);
            }

            List<LantopReportField> lrfListAll = (List<LantopReportField>) getListByColumnValue(LantopReportField.class, "reportId", id);
            if (lrfListAll.size() > 0) {
                hibernateDao.deleteAll(lrdListAll);
                SysLogUtil.log("表报管理模块", "删除记录", OpType.delete, OpResult.success, LogBaseFactory.getLogBase());
            }

            outputFields = outputFields.substring(0, outputFields.length() - 1);
            List<LantopReportField> lrfList = createLantopReportFieldObject(sysId, id, outputFields);
            for (LantopReportField lrf : lrfList) {
                hibernateDao.save(lrf);
                SysLogUtil.log(lrf, null, OpType.insert, OpResult.success);
            }

            // 如果成功， 则通过Map带出一个模板ID的
            paramsMap.put("___templateId", id);

        } catch (Exception e) {
            logger.error("saveDataBaseConfigForTable error,  ", e);
            success = false;
        }

        return success;
    }

    @Override
    public List<String> findUseCustomDataSourceFields(String reportId, Map<String, Object> paramsMap) {
//		String sysId = (String) paramsMap.get("sysId");

        List<String> columnList = new ArrayList<String>();

        List<LantopReportField> lrfList = (List<LantopReportField>) getListByColumnValue(LantopReportField.class, "reportId", reportId);
        for (LantopReportField lrf : lrfList) {
            columnList.add(lrf.getFieldChinese());

        }

        return columnList;
    }

    @Override
    public List<String> findDataSourceFields(String reportId, Map<String, Object> paramsMap) {
//		String sysId = (String) paramsMap.get("sysId");

        List<String> columnList = new ArrayList<String>();

        List<LantopReportSetField> lrsfList = (List<LantopReportSetField>) getListByColumnValue(LantopReportSetField.class, "reportId", reportId);
        for (LantopReportSetField lrsf : lrsfList) {
            columnList.add(lrsf.getFieldChinese());
        }

        return columnList;
    }

    @Override
    public List<Map<String, Object>> findReportSetField(Map<String, String> argsMaps) {
        String sysId = argsMaps.get("sysId");
        String orgId = argsMaps.get("orgId");
        String reportId = argsMaps.get("reportId");
        String tabelName = argsMaps.get("tableName");
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT CT.TABLE_TITLE, t.* " + "  FROM LANTOP_REPORT_SET_FIELD t LEFT JOIN CBB_TABLES CT ON CT.TABLE_NAME = T.TABLE_NAME" + "  WHERE 1=1 ");
        if (null != sysId) {
            sql.append(" AND t.SYS_ID='" + sysId + "'");
        }
        if (null != orgId) {
            sql.append(" AND t.ORG_ID='" + orgId + "' AND CT.ORG_ID='"+orgId+"'");
        }
        if (null != reportId) {
            sql.append(" AND t.REPORT_ID='" + reportId + "'");
        }
        if (null != tabelName) {
            String[] tableNameTmpArray = tabelName.split(",");
            if (tableNameTmpArray.length > 1) {
                // 两张表
                sql.append(" AND t.ATTRIBUTE_01 = '" + tableNameTmpArray[0] + "," + tableNameTmpArray[1] + "'");
            } else {
                // 一张表
                sql.append(" AND t.TABLE_NAME = '" + tabelName + "' AND T.ATTRIBUTE_01 IS NULL");
            }
        }
        sql.append(" ORDER BY t.FIELD_SERIAL ");
        return jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
    }

    @Override
    public List<Map<String, Object>> findDataSource(Map<String, String> argsMaps) {
        String sysId = argsMaps.get("sysId");
//		String reportId = argsMaps.get("reportId");
        String tableId = argsMaps.get("tableId");
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT TT.COL_NAME, T.TABLE_ID, T.COLUMN_ID, T.SORT_ORDER, T.SORT_CODE FROM CBB_TAB_COL_SORT T LEFT JOIN CBB_TAB_COLUMNS TT ON TT.ID = T.COLUMN_ID");
        sql.append(" WHERE T.TABLE_ID = '" + tableId + "' AND T.SYS_ID = '" + sysId + "' ORDER BY SORT_ORDER");
        return jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
    }

    @Override
    public List<TreeNode> findTreeByTableName(Map<String, Object> paramsMap) {
        String sysId = (String) paramsMap.get("sysId");
        String tableName = (String) paramsMap.get("tableNames");
        String type = (String) paramsMap.get("type");
        String orgId = (String) paramsMap.get("orgId");
//		String orgIdentity = (String) paramsMap.get("orgIdentity");
        if(type.equals("root")){
            orgId = "ORG_ROOT";
//			orgIdentity = "ORG_ROOT";
        }
        Map<String,Object> orgInfo = getOrgInfoById(orgId);


        StringBuffer sql = new StringBuffer();
        sql.append("SELECT DISTINCT t.REPORT_ID " + "   FROM LANTOP_REPORT_SET_FIELD t " + "   WHERE 1=1");
        if (null != sysId) {
            sql.append(" AND t.SYS_ID='" + sysId + "'");
        }
        if (null != tableName) {
            String tableNameTmp = "";
            String[] tableNameTmpArray = tableName.split(",");
            for (String table : tableNameTmpArray) {
                tableNameTmp = tableNameTmp + "'" + table + "'" + ",";
            }
            tableNameTmp = tableNameTmp.substring(0, tableNameTmp.length() - 1);
            sql.append(" AND t.TABLE_NAME IN(" + tableNameTmp + ")");
        }
	/*	if(null != orgId){
			sql.append("   AND T.ORG_ID = '"+orgId+"' ");
		}*/

        List<Map<String, Object>> resultList = jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
        String reportIds = "";
        for (Map<String, Object> map : resultList) {
            String reportId = (String) map.get("REPORT_ID");
            reportIds = reportIds + "'" + reportId + "',";
        }
        if (reportIds.length() == 0) {
            return new ArrayList<TreeNode>();
        }
        reportIds = reportIds.substring(0, reportIds.length() - 1);
        // 使用Oracle的递归查询，查询树的节点的层级关系
        sql = new StringBuffer("");
        sql.append("SELECT * " + "	FROM LANTOP_REPORT_BASETABLE t " + "   CONNECT BY PRIOR t.PARENT_ID = t.ID " + "   START WITH t.ID IN (" + reportIds + ") ");
        sql.append(" AND T.ORG_ID = '"+orgId+"'");
        sql.append(" order siblings by t.attribute_11 desc ");
        List<TreeNode> nodeList = new ArrayList<TreeNode>();
        List<Map<String, Object>> treeList = jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
        TreeNode tn = new TreeNode();
        if (treeList.size() > 0) {
            List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
            for (Map<String, Object> map : treeList) {
                if (!newList.contains(map)) {
                    newList.add(map);
                }
            }
            Map<String, Object> treeMap = treeList.get(treeList.size() - 1);
            tn.setId((String) treeMap.get("ID"));
            tn.set_parentId((String) treeMap.get("PARENT_ID"));
            if(treeMap.get("PARENT_ID").equals("-1")){
                tn.setText(orgInfo.get("TEMP_NAME").toString());
            }else{
                tn.setText((String) treeMap.get("REPORT_NAME"));
            }
            String cptFileName = (String) treeMap.get("ATTRIBUTE_01");
            HashMap<String, Object> attr = new HashMap<String, Object>();
            attr.put("cptFileName", cptFileName);
            // 获取节点的类型
            String idType = (String) treeMap.get("REPORT_TYPE");
            if ("0".equals(idType)) {
                // 表示是分类信息
                tn.setIconCls("icon-im-newnmodulefile");
            } else {
                // 如果是模板信息，则需要额外的查询下该模板是否已经进行了数据源配置
                List<?> lrfList = getListByColumnValue(LantopReportField.class, "reportId", tn.getId());
                if (lrfList.size() == 0) {
                    // 没有配置过字段信息
                    attr.put("hasField", false);
                } else {
                    attr.put("hasField", true);

                    String fields = "";
                    for (Object obj : lrfList) {
                        LantopReportField lrf = (LantopReportField) obj;
                        fields = fields + lrf.getFieldChinese() + ",";
                    }
                    // 去掉最后一个,
                    fields = fields.substring(0, fields.length() - 1);
                    attr.put("fields", fields);
                    // 查询 LantopReportSetField 表中有关表信息
                    List<?> lrsfList = getListByColumnValue(LantopReportSetField.class, "reportId", tn.getId());
                    if (lrsfList.isEmpty() == false) {
                        String selectTableNames = "";
                        for (int j = 0; j < lrsfList.size(); j++) {
                            LantopReportSetField lrsf = (LantopReportSetField) lrsfList.get(j);
                            String tableName1 = lrsf.getTableName();
                            if (selectTableNames.contains(tableName1)) {
                                continue;
                            }
                            selectTableNames = selectTableNames + lrsf.getTableName() + ",";
                        }
                        selectTableNames = selectTableNames.substring(0, selectTableNames.length() - 1);
                        attr.put("resultDataSource", selectTableNames);
                    }
                }
            }
            attr.put("reportType", idType);
            tn.setAttributes(attr);
            this.getTreeNodeList(newList, tn);
        }
        nodeList.add(tn);
        return nodeList;
    }

    public void getTreeNodeList(List<Map<String, Object>> treeList, TreeNode parentTn) {
        List<TreeNode> tnList = new ArrayList<TreeNode>();
        for (int i = treeList.size() - 1; i >= 0; i--) {
            Map<String, Object> treeMap = treeList.get(i);
            if (treeMap.get("PARENT_ID").equals(parentTn.getId())) {
                TreeNode tn = new TreeNode();
                tn.setId((String) treeMap.get("ID"));
                tn.set_parentId((String) treeMap.get("PARENT_ID"));
                tn.setText((String) treeMap.get("REPORT_NAME"));
                this.getTreeNodeList(treeList, tn);
                String cptFileName = (String) treeMap.get("ATTRIBUTE_01");
                HashMap<String, Object> attr = new HashMap<String, Object>();
                attr.put("cptFileName", cptFileName);
                // 获取节点的类型
                String idType = (String) treeMap.get("REPORT_TYPE");
                if ("0".equals(idType)) {
                    // 表示是分类信息
                    tn.setIconCls("icon-im-newnmodulefile");
                } else {
                    // 如果是模板信息，则需要额外的查询下该模板是否已经进行了数据源配置
                    List<?> lrfList = getListByColumnValue(LantopReportField.class, "reportId", tn.getId());
                    if (lrfList.size() == 0) {
                        // 没有配置过字段信息
                        attr.put("hasField", false);
                    } else {
                        attr.put("hasField", true);

                        String fields = "";
                        for (Object obj : lrfList) {
                            LantopReportField lrf = (LantopReportField) obj;
                            fields = fields + lrf.getFieldChinese() + ",";
                        }
                        // 去掉最后一个,
                        fields = fields.substring(0, fields.length() - 1);
                        attr.put("fields", fields);
                        // 查询 LantopReportSetField 表中有关表信息
                        List<?> lrsfList = getListByColumnValue(LantopReportSetField.class, "reportId", tn.getId());
                        if (lrsfList.isEmpty() == false) {
                            String selectTableNames = "";
                            for (int j = 0; j < lrsfList.size(); j++) {
                                LantopReportSetField lrsf = (LantopReportSetField) lrsfList.get(j);
                                String tableName1 = lrsf.getTableName();
                                if (tableName1 == null || selectTableNames.contains(tableName1)) {
                                    continue;
                                }
                                selectTableNames = selectTableNames + lrsf.getTableName() + ",";
                            }
                            selectTableNames = selectTableNames.substring(0, selectTableNames.length() - 1);
                            attr.put("resultDataSource", selectTableNames);
                        }
                    }
                }
                attr.put("reportType", idType);
                tn.setAttributes(attr);
                tnList.add(tn);
            }
        }
        parentTn.setChildren(tnList);
    }

    /**
     * TODO 根据模板ID和模板名称获取报表集合
     *
     * @param paramsMap
     * @return List<Map<String,Object>>
     * @throws
     */
    public List<Map<String, Object>> checkExistsByReportIdAndReportName(Map<String, Object> paramsMap) {
        String sysId = (String) paramsMap.get("sysId");
        String reportId = (String) paramsMap.get("reportId");
        String tableName = (String) paramsMap.get("tableName");
        String attribute01 = (String) paramsMap.get("attribute01");
        // 表示不存在数据
        if (null == reportId || "".equals(reportId)) {
            return null;
        }

        StringBuffer sql = new StringBuffer();
        sql.append("SELECT * " + "   FROM LANTOP_REPORT_SET_FIELD t " + "   WHERE 1 = 1 ");
        if (null != sysId && (!"".equals(sysId))) {
            sql.append(" AND t.SYS_ID='" + sysId + "' ");
        }
        if (null != reportId && (!"".equals(reportId))) {
            sql.append(" AND t.REPORT_ID='" + reportId + "' ");
        }
        if (null != tableName && (!"".equals(tableName))) {
            sql.append(" AND t.TABLE_NAME='" + tableName + "' ");
            sql.append(" AND (t.ATTRIBUTE_01 IS NULL OR t.ATTRIBUTE_01 = '')");
        }
        if (null != attribute01 && (!"".equals(attribute01))) {
            String[] tableNameTmpArray = attribute01.split(",");
            String tableNameRevers = "";
            for (int i = tableNameTmpArray.length - 1; i >= 0; i--) {
                tableNameRevers = tableNameRevers + tableNameTmpArray[i] + ",";
            }
            tableNameRevers = tableNameRevers.substring(0, tableNameRevers.length() - 1);
            sql.append(" AND (t.ATTRIBUTE_01='" + attribute01 + "' OR t.ATTRIBUTE_01='" + tableNameRevers + "')");

        }

        return jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());

    }

    /**
     * TODO 查找某一节点是否存在
     *
     * @param nodeList
     *            树结构
     * @param treeNode
     *            要查找的节点
     * @return boolean 是否存在
     * @throws
     */
    public boolean findTreeNodeExits(List<TreeNode> nodeList, TreeNode treeNode) {

        for (TreeNode node : nodeList) {
            if (node.getId().equals(treeNode.getId())) {
                return true;
            } else {
                if (node.getChildren().size() > 0) {
                    return findTreeNodeExits(node.getChildren(), treeNode);
                }
            }

        }

        return false;

    }

    /**
     * TODO 找某一节点的父节点
     *
     * @param nodeList
     *            树行结构
     * @param treeNode
     *            要查找的节点
     * @return TreeNode 查找到的父节点
     * @throws
     */
    public TreeNode findTreeNodeById(List<TreeNode> nodeList, TreeNode treeNode) {
        for (TreeNode node : nodeList) {
            if (node.getId().equals(treeNode.get_parentId())) {
                return node;
            } else {
                if (node.getChildren().size() > 0) {
                    return findTreeNodeById(node.getChildren(), treeNode);
                }
            }

        }
        return null;
    }

    // 根据ReportId，删除已经配置过的字段信息
    @Override
    public boolean deleteSetField(Map<String, Object> paramsMap) {
        boolean success = true;
        String ids = (String) paramsMap.get("ids");
        String talbleName = (String) paramsMap.get("tableName");

        String[] idss = ids.split(",");
        for (String id : idss) {
            // 先查找, 然后删除
            List<LantopReportSetField> lrsfList = (List<LantopReportSetField>) getListByColumnValue(LantopReportSetField.class, "reportId", id);

            for (LantopReportSetField lrsf : lrsfList) {
                if (null != lrsf && talbleName.equals(lrsf.getTableName())) {
                    try {
                        hibernateDao.delete(lrsf);
                        SysLogUtil.log(lrsf, null, OpType.delete, OpResult.success);
                    } catch (Exception e) {
                        success = false;
                        logger.error("delete error LantopReportField id : " + id, e);
                    }
                }
            }
        }

        return success;
    }

    /**
     * 查询二维码规则信息
     *
     * @param nodeId
     * @return
     * @throws
     */
    @Override
    public List<Map<String, Object>> findRuleInfoById(String nodeId) {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("select t.ID,\n");
        sbSql.append("		 t.ARCHIVE_TABLE_ID,\n");
        sbSql.append("		 t.LANTOP_ARCHIVE_CLASS_ID,\n");
        sbSql.append("       t.ARCHIVE_TABLE_NAME,\n");
        sbSql.append("       t.ARCHIVE_TABLE_TITLE,\n");
        sbSql.append("       t.COND_EXPRESS_EN,\n");
        sbSql.append("       t.COND_EXPRESS_CN\n");
        sbSql.append("from lantop_bar_code_rule t\n");
        sbSql.append("where t.LANTOP_ARCHIVE_CLASS_ID = '");
        sbSql.append(nodeId);
        sbSql.append("'");
        List<Map<String, Object>> list = jdbcAvicit.queryForMap(sbSql.toString(), null);
        return list;
    }

    /**
     * 根据表ID获取二维码规则信息
     *
     * @author 郭亮
     * @param tableId
     * @return List<Map<String,Object>>
     */
    @Override
    public List<Map<String, Object>> findRuleInfoByTableId(String tableId) {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("select t.ID,\n");
        sbSql.append("		 t.ARCHIVE_TABLE_ID,\n");
        sbSql.append("		 t.BAR_CODE_RULE_TYPE,\n");
        sbSql.append("		 t.LANTOP_ARCHIVE_CLASS_ID,\n");
        sbSql.append("       t.ARCHIVE_TABLE_NAME,\n");
        sbSql.append("       t.ARCHIVE_TABLE_TITLE,\n");
        sbSql.append("       t.COND_EXPRESS_EN,\n");
        sbSql.append("       t.COND_EXPRESS_CN\n");
        sbSql.append("from lantop_bar_code_rule t\n");
        sbSql.append("where t.ARCHIVE_TABLE_ID = '");
        sbSql.append(tableId);
        sbSql.append("'");
        List<Map<String, Object>> list = jdbcAvicit.queryForMap(sbSql.toString(), null);
        return list;
    }

    @Override
    public List<Map<String, Object>> findRuleInfoByTableId(String tableId, String nodeId) {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("select t.ID,\n");
        sbSql.append("		 t.ARCHIVE_TABLE_ID,\n");
        sbSql.append("		 t.BAR_CODE_RULE_TYPE,\n");
        sbSql.append("		 t.LANTOP_ARCHIVE_CLASS_ID,\n");
        sbSql.append("       t.ARCHIVE_TABLE_NAME,\n");
        sbSql.append("       t.ARCHIVE_TABLE_TITLE,\n");
        sbSql.append("       t.COND_EXPRESS_EN,\n");
        sbSql.append("       t.COND_EXPRESS_CN\n");
        sbSql.append("from lantop_bar_code_rule t\n");
        sbSql.append("where t.ARCHIVE_TABLE_ID = '" + tableId + "' and t.LANTOP_ARCHIVE_CLASS_ID = '" + nodeId + "'");
        List<Map<String, Object>> list = jdbcAvicit.queryForMap(sbSql.toString(), null);
        return list;
    }

    /**
     * 根据报表ID查找Name
     *
     * @author gl
     * @param reportId
     * @return
     * @throws Exception
     */
    public String getReportRealNameById(String reportId) throws Exception {
        String reportRealName = "";
        if (null == reportId || "".equals(reportId) || "null".equals(reportId)) {
            throw new Exception("调用方法时reportId参数不存在，请检查！");
        }
        String sql = "SELECT LRB.ATTRIBUTE_01 FROM LANTOP_REPORT_BASETABLE LRB WHERE LRB.ID = '" + reportId + "'";
        List<Object> list = this.hibernateDao.findBySQL(sql);
        if (list.size() > 0) {
            reportRealName = String.valueOf(list.get(0));
        }
        return reportRealName;
    }

    /**
     * 删除模块对应关系
     *
     * @param reportId
     * @param tableName
     * @throws Exception
     * @throws
     */
    public void deleteReportRelation(String reportId, String tableName,String orgId) throws Exception {
        String[] tableNameArray = tableName.split(",");
        tableName = tableNameArray[0];
        String sql = "delete from lantop_report_set_field " +
                "where report_id = '" + reportId + "' " +
                "and table_name = '" + tableName + "' " +
                "AND ORG_ID = '"+orgId+"'";
        this.jdbcAvicit.getJdbcTemplate().execute(sql);
    }

    public List<Map<String, Object>> getPublicFieldInfo() {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("WITH T1 AS\n");
        sbSql.append(" (SELECT\n");
        sbSql.append("   LAC.ID,\n");
        sbSql.append("   LAC.ARCHIVE_CLASS_NODE_CODE AS ARCHIVE_CLASS_NODE_CODE,\n");
        sbSql.append("   LAC.ARCHIVE_CLASS_NODE_NAME AS ARCHIVE_CLASS_NODE_NAME,\n");
        sbSql.append("   '-1' AS TABLE_NAME,\n");
        sbSql.append("   LAC.PARENT_ID,\n");
        sbSql.append("   LAC.ARCHIVE_TYPE,\n");
        sbSql.append("   LAC.ARCHIVE_CLASS_NODE_TYPE,\n");
        sbSql.append("   LAC.IS_VISIBLE,\n");
        sbSql.append("   LAC.NODE_SORT_NUMBER,\n");
        sbSql.append("   LAC.RELAT_WORKFLOW,\n");
        sbSql.append("   LAC.TABLE_LAYER,\n");
        sbSql.append("   LAC.ARCHIVE_CLASS_NODE_PATH,\n");
        sbSql.append("   LAC.REMARK,\n");
        sbSql.append("   LAC.ORG_ID,\n");
        sbSql.append("   LAC.DEPT_ID,\n");
        sbSql.append("   LAC.SYS_ID,\n");
        sbSql.append("   LAC.SECRET_LEVEL,\n");
        sbSql.append("   LAC.SYS_APPLICATION_ID,\n");
        sbSql.append("   LAC.CREATED_BY,\n");
        sbSql.append("   LAC.CREATION_DATE,\n");
        sbSql.append("   LAC.LAST_UPDATED_BY,\n");
        sbSql.append("   LAC.LAST_UPDATE_DATE,\n");
        sbSql.append("   LAC.LAST_UPDATE_IP,\n");
        sbSql.append("   LAC.VERSION,\n");
        sbSql.append("   LAC.ATTRIBUTE_01,\n");
        sbSql.append("   LAC.ATTRIBUTE_02,\n");
        sbSql.append("   LAC.ATTRIBUTE_03,\n");
        sbSql.append("   LAC.ATTRIBUTE_04,\n");
        sbSql.append("   LAC.ATTRIBUTE_05,\n");
        sbSql.append("   LAC.ATTRIBUTE_06,\n");
        sbSql.append("   LAC.ATTRIBUTE_07,\n");
        sbSql.append("   LAC.ATTRIBUTE_08,\n");
        sbSql.append("   LAC.ATTRIBUTE_09,\n");
        sbSql.append("   LAC.ATTRIBUTE_10,\n");
        sbSql.append("   LAC.ATTRIBUTE_11,\n");
        sbSql.append("   LAC.ATTRIBUTE_12,\n");
        sbSql.append("   LAC.ATTRIBUTE_13,\n");
        sbSql.append("   LAC.ATTRIBUTE_14,\n");
        sbSql.append("   LAC.ATTRIBUTE_15,\n");
        sbSql.append("   -1 AS TAB_ORDER,\n");
        sbSql.append("   0 AS MAP_SET_TGT_COUNT,\n");
        sbSql.append("   0 AS MAP_SET_TGT_PUB_COUNT,\n");
        sbSql.append("   '' AS IS_TRUE_TABLE\n");
        sbSql.append("    FROM LANTOP_ARCHIVE_CLASS LAC\n");
        sbSql.append("   WHERE LAC.ARCHIVE_CLASS_NODE_TYPE = ''\n");
        sbSql.append("      OR LAC.ARCHIVE_CLASS_NODE_TYPE IS NULL),\n");
        sbSql.append("T2 AS\n");
        sbSql.append(" (SELECT *\n");
        sbSql.append("    FROM T1\n");
        sbSql.append("  UNION ALL\n");
        sbSql.append("  SELECT CT.ID,\n");
        sbSql.append("         T1.ARCHIVE_CLASS_NODE_CODE AS ARCHIVE_CLASS_NODE_CODE,\n");
        sbSql.append("         CT.TABLE_TITLE AS ARCHIVE_CLASS_NODE_NAME,\n");
        sbSql.append("         CT.TABLE_NAME AS TABLE_NAME,\n");
        sbSql.append("         T1.ID AS PARENT_ID,\n");
        sbSql.append("         '-1' AS ARCHIVE_TYPE,\n");
        sbSql.append("         T1.ARCHIVE_CLASS_NODE_TYPE,\n");
        sbSql.append("         T1.IS_VISIBLE,\n");
        sbSql.append("         CTN.TAB_ORDER AS NODE_SORT_NUMBER,\n");
        sbSql.append("         T1.RELAT_WORKFLOW,\n");
        sbSql.append("         T1.TABLE_LAYER,\n");
        sbSql.append("         T1.ARCHIVE_CLASS_NODE_PATH || '/' || CT.ID AS ARCHIVE_CLASS_NODE_PATH,\n");
        sbSql.append("         T1.REMARK,\n");
        sbSql.append("         T1.ORG_ID,\n");
        sbSql.append("         T1.DEPT_ID,\n");
        sbSql.append("         T1.SYS_ID,\n");
        sbSql.append("         T1.SECRET_LEVEL,\n");
        sbSql.append("         T1.SYS_APPLICATION_ID,\n");
        sbSql.append("         T1.CREATED_BY,\n");
        sbSql.append("         T1.CREATION_DATE,\n");
        sbSql.append("         T1.LAST_UPDATED_BY,\n");
        sbSql.append("         T1.LAST_UPDATE_DATE,\n");
        sbSql.append("         T1.LAST_UPDATE_IP,\n");
        sbSql.append("         T1.VERSION,\n");
        sbSql.append("         T1.ATTRIBUTE_01,\n");
        sbSql.append("         T1.ATTRIBUTE_02,\n");
        sbSql.append("         T1.ATTRIBUTE_03,\n");
        sbSql.append("         T1.ATTRIBUTE_04,\n");
        sbSql.append("         T1.ATTRIBUTE_05,\n");
        sbSql.append("         T1.ATTRIBUTE_06,\n");
        sbSql.append("         T1.ATTRIBUTE_07,\n");
        sbSql.append("         T1.ATTRIBUTE_08,\n");
        sbSql.append("         T1.ATTRIBUTE_09,\n");
        sbSql.append("         T1.ATTRIBUTE_10,\n");
        sbSql.append("         T1.ATTRIBUTE_11,\n");
        sbSql.append("         T1.ATTRIBUTE_12,\n");
        sbSql.append("         T1.ATTRIBUTE_13,\n");
        sbSql.append("         T1.ATTRIBUTE_14,\n");
        sbSql.append("         T1.ATTRIBUTE_15,\n");
        sbSql.append("         CTN.TAB_ORDER,\n");
        sbSql.append("         (SELECT COUNT(*)\n");
        sbSql.append("            FROM LANTOP_FIELD_RELATE_SET LFRS\n");
        sbSql.append("           WHERE LFRS.TGT_TABLE_ID = CT.ID) AS MAP_SET_TGT_COUNT,\n");
        sbSql.append("         (SELECT COUNT(*)\n");
        sbSql.append("            FROM LANTOP_FIELD_RELATE_SET LFRS\n");
        sbSql.append("           WHERE LFRS.TGT_TABLE_NAME = 'LANTOP_PUB_FIELD'\n");
        sbSql.append("             AND LFRS.SOURCE_TABLE_ID = CT.ID) AS MAP_SET_TGT_PUB_COUNT,\n");
        sbSql.append("         CT.TABLE_IS_TRUE_TABLE AS IS_TRUE_TABLE\n");
        sbSql.append("    FROM T1\n");
        sbSql.append("   INNER JOIN CBB_TAB_NODE CTN\n");
        sbSql.append("      ON T1.ID = CTN.NODE_ID\n");
        sbSql.append("   INNER JOIN CBB_TABLES CT\n");
        sbSql.append("      ON CTN.TABLE_ID = CT.ID\n");
        sbSql.append("\n");
        sbSql.append("  )\n");
        sbSql.append("SELECT T2.*\n");
        sbSql.append("  FROM T2\n");
        sbSql.append(" WHERE ARCHIVE_CLASS_NODE_CODE = 'LANTOP_PUB_FIELD'\n");
        sbSql.append(" ORDER BY T2.TAB_ORDER");
        return this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
    }

    /**
     * 递归获取Tree当前节点下数据
     *
     * @param id
     *            当前节点
     * @param level
     *            需要获取的层数
     * @return 节点集合
     */
    public List<TreeNode> recurFindTreeNodesByParentId(String id, int level, String orgId) {

        // 递归一层减一层
        --level;

        List<TreeNode> nodes = new ArrayList<TreeNode>();

        // 查询业务数据
        List<Map<String, Object>> childTreeList = findNodesByParentId(id, orgId);

        // 将业务数据格式转换成esayui树形格式
        for (Map<String, Object> row : childTreeList) {
            String rid = (String) row.get("ID");
            String rname = (String) row.get("ARCHIVE_CLASS_NODE_NAME");
            String nodeType = (String) row.get("ARCHIVE_CLASS_NODE_TYPE");
            String archiveType = (String) row.get("ARCHIVE_TYPE");
            String parentId = (String) row.get("PARENT_ID");
            TreeNode node = new TreeNode();
            node.setId(rid);
            node.setText(rname);
            // 根据节点类型,设置节点图标
            if (null != parentId && "ROOT".equals(parentId)) { // 根节点
                node.setIconCls("icon-im-newnorg");
            } else if (null != archiveType && "-1".equals(archiveType)) { // -1
                // 档案类型
                // 物理表
                node.setIconCls("icon-im-newntable");
            } else if (null != archiveType && "0".equals(archiveType)) { // 0模版文件夹
                node.setIconCls("icon-im-newnmodulefile");
            } else if (null != archiveType && "1".equals(archiveType)) { // 1标识文件
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "2".equals(archiveType)) { // 2 档案
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "3".equals(archiveType)) { // 3
                // 专题库
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "4".equals(archiveType)) { // 4
                // 多媒体
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "5".equals(archiveType)) { // 5
                // 项目归档计划
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "6".equals(archiveType)) { // 6 管务
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "7".equals(archiveType)) { // 7 其他
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "8".equals(archiveType)) { // 8 资料
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "9".equals(archiveType)) { // 9 图书
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "10".equals(archiveType)) { // 10
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != nodeType && "1".equals(nodeType)) { // 节点类型 1 文件夹
                node.setIconCls("icon-im-newnmodulefile");
            } else if (null != nodeType && "2".equals(nodeType)) { // 数据节点
                node.setIconCls("icon-im-newntable");
            } else if (null != archiveType && "TECH".equals(archiveType)) { // 10
                node.setIconCls("icon-im-newnmodulelib");
            }
            node.setAttributes(row);
            node.set_parentId((String) row.get("PARENT_ID"));

            BigDecimal childCount2 = BigDecimal.valueOf(Long.valueOf(row.get("CHILD_COUNT") + ""));
            if (null != childCount2 && childCount2.longValue() > 0) {
                if (level > 0) {
                    List<TreeNode> cnodes = recurFindTreeNodesByParentId(rid, level, orgId);
                    node.getChildren().addAll(cnodes);
                    node.setState("open");
                } else {
                    node.setState("closed");
                }
            } else {
                node.setState("open");
            }
            nodes.add(node);
        }
        return nodes;
    }

    /**
     * 获取子节点
     *
     * @param parentId
     * @return
     */
    public List<Map<String, Object>> findNodesByParentId(String parentId, String orgId) {
        Assert.notNull(parentId, "参数不能为空！");
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT (SELECT COUNT(*)\n");
        sbSql.append("          FROM LANTOP_ARCHIVE_TAB_CLASS_V D2\n");
        sbSql.append("         WHERE D2.PARENT_ID = D1.ID) CHILD_COUNT,\n");
        sbSql.append("       D1.*\n");
        sbSql.append("  FROM LANTOP_ARCHIVE_TAB_CLASS_V D1\n");
        sbSql.append(" WHERE D1.PARENT_ID = ? AND ORG_ID = ? AND (D1.ARCHIVE_TYPE <> '-1' OR D1.ARCHIVE_TYPE IS NULL) \n");
        sbSql.append(" ORDER BY D1.NODE_SORT_NUMBER ASC,D1.CREATION_DATE ASC");
        return this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString(), parentId, orgId);
    }

    public List<Map<String, Object>> findTablesByNodeId(String nodeId,String orgId) {
        String sql = "SELECT * FROM LANTOP_ARCHIVE_TAB_CLASS_V T WHERE T.PARENT_ID = '" + nodeId + "' AND  T.ORG_ID = '"+orgId+"' ORDER BY NODE_SORT_NUMBER ASC";
        return this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
    }

    /**
     * 保存报表临时数据表信息
     *
     * @param reportTemplate
     * @return String
     * @throws
     */
    public String saveReportTemplate(LantopReportTemplate reportTemplate) {
        String id = ComUtil.getId();
        reportTemplate.setId(id);
        PojoUtil.setSysProperties(reportTemplate, OpType.insert);
        this.hibernateDao.save(reportTemplate);
        SysLogUtil.log(reportTemplate, null, OpType.insert, OpResult.success);
        return id;
    }

    /**
     * 通过id获取报表临时表数据
     *
     * @param id
     * @return LantopReportTemplate
     * @throws
     */
    public LantopReportTemplate getLantopReportTemplateById(String id) {
        return this.hibernateDao.get(LantopReportTemplate.class, id);
    }

    public void deleteLantopReportTemplate() {
        String sql = "delete from lantop_report_template";
        System.out.println("清理报表临时表数据");
        this.jdbcAvicit.getJdbcTemplate().update(sql);
    }

    /**
     * 报表模板配置规则子表查询
     *
     * @param configType
     *            配置类型
     * @param templateId
     *            报表模板Id
     * @param sysId
     *            系统ID
     * @return List<Map<String, Object>>
     * @throws Exception
     */
    public Paging<LantopReportConfigDetails> getReportConfig(Paging<LantopReportConfigDetails> page, Map<String, Object> parameter) throws Exception {
        List<PropertyFilter> filters = PropertyFilter.buildFromParameterMap(parameter);
        String hql = " from LantopReportConfigDetails ";
        HashMap<String, Object> ValueMap = new HashMap<String, Object>();
        if (null != parameter) {
            hql = hibernateDao.buildDynamicHql(filters, hql, ValueMap);
        }
        Paging<LantopReportConfigDetails> paging = hibernateDao.findPage(page, hql, ValueMap);
        return paging;
    }

    /**
     * 通过报表模板id查询报表配置规则主表
     * @param tempLateId
     * @return String
     */
    public String findLantopReportConfigurationByTemplateId(String templateId) {
        String reportConfigPid = null;
        String sql = "SELECT T.ID FROM LANTOP_REPORT_CONFIGURATION T WHERE T.REPORT_TEMPLATE_ID = ? ";
        List<Map<String, Object>> list = jdbcAvicit.getJdbcTemplate().queryForList(sql, templateId);
        if (list.size() > 0) {
            reportConfigPid = (String) list.get(0).get("ID");
        }
        return reportConfigPid;
    }

    /**
     * 通过子表id查询主表
     * @param id
     * @return String
     */
    public String findLantopReportConfigurationIdById(String id) {
        String reportConfigPid = null;
        String sql = "SELECT T.REPORT_CONFIG_ID FROM LANTOP_REPORT_CONFIG_DETAILS T WHERE T.ID = ?";
        List<Map<String, Object>> list = jdbcAvicit.getJdbcTemplate().queryForList(sql, id);
        if (list.size() > 0) {
            reportConfigPid = (String) list.get(0).get("REPORT_CONFIG_ID");
        }
        return reportConfigPid;
    }

    /**
     * 通过主表id查询子表数据个数
     * @param id
     * @return int
     */
    public int findLantopReportConfigDetailsByPid(String pid) {
        int count = 0;
        String sql = "SELECT T.ID FROM LANTOP_REPORT_CONFIG_DETAILS T WHERE T.REPORT_CONFIG_ID = ?";
        List<Map<String, Object>> list = jdbcAvicit.getJdbcTemplate().queryForList(sql, pid);
        if (list.size() > 0) {
            count = list.size();
        }
        return count;
    }

    /**
     * 保存报表模板配置主表
     * @param bean
     */
    public void saveLantopReportConfiguration(BeanBase bean) {
        LantopReportConfiguration dto = (LantopReportConfiguration) bean;
        if (null == dto) {
            throw new DaoException(dto.toString() + "对象转换出错！");
        }
        dto.setId(ComUtil.getId());
        PojoUtil.setSysProperties(dto, OpType.insert);
        hibernateDao.save(dto);
        SysLogUtil.log(dto, null, OpType.insert, OpResult.success);
    }

    /**
     * 报表模板配置规则保存子表
     *
     * @param configType
     */
    public void saveReportConfig(BeanBase bean) {
        LantopReportConfigDetails dto = (LantopReportConfigDetails) bean;
        if (null == dto) {
            throw new DaoException(dto.toString() + "对象转换出错！");
        }
        dto.setId(ComUtil.getId());
        PojoUtil.setSysProperties(dto, OpType.insert);
        hibernateDao.save(dto);
        SysLogUtil.log(dto, null, OpType.insert, OpResult.success);
    }

    /**
     * 报表模板配置规则更新子表
     *
     * @param bean
     */
    public void updateReportConfig(BeanBase bean) {
        LantopReportConfigDetails dto = (LantopReportConfigDetails) bean;
        if (null == dto) {
            throw new DaoException(dto.toString() + "对象转换出错！");
        }
        LantopReportConfigDetails oldDto = hibernateDao.get(LantopReportConfigDetails.class, dto.getId());
        hibernateDao.evict(oldDto);
        LantopReportConfigDetails temp = oldDto;
        try {
            PojoUtil.copyProperties(temp, dto, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PojoUtil.setSysProperties(temp, OpType.update);
        hibernateDao.update(temp);
        SysLogUtil.log(dto, oldDto, OpType.update, OpResult.success);
    }

    /**
     * 报表模板配置规则子表根据id删除数据
     *
     * @param ids
     */
    public void deleteReportConfigByIds(String ids) {
        Assert.notNull(ids);
        String[] idArray = ids.split(",");
        for (int i = 0; i < idArray.length; i++) {
            deleteLantopReportConfigDetailsById(idArray[i]);
        }
    }

    /**
     * 根据id删除报表模板配置规则子表
     * @param id
     * @return LantopReportConfigDetails
     * @throws
     */
    public void deleteLantopReportConfigDetailsById(String id) {
        LantopReportConfigDetails dto = (LantopReportConfigDetails) hibernateDao.getSession().get(LantopReportConfigDetails.class, id);
        if (dto == null) {
            throw new DaoException("LantopReportConfigDetails对象不存在！");
        }
        hibernateDao.delete(dto);
        SysLogUtil.log(dto, null, OpType.delete, OpResult.success);
    }

    /**
     * 根据id删除报表模板配置规则主表
     * @param id
     * @return LantopReportConfigDetails
     * @throws
     */
    public void deleteLantopReportConfigurationById(String id) {
        LantopReportConfiguration dto = (LantopReportConfiguration) hibernateDao.getSession().get(LantopReportConfiguration.class, id);
        if (dto == null) {
            throw new DaoException("LantopReportConfiguration对象不存在！");
        }
        hibernateDao.delete(dto);
        SysLogUtil.log(dto, null, OpType.delete, OpResult.success);
    }

    /**
     * 主表id子表查询
     * @param id,configType
     * @return List<Map<String, Object>>
     */
    public List<Map<String, Object>> findLantopReportConfigDetailsByTemplateId(String pid, String configType) {
        String sql = "SELECT T.CONFIG_FIELD_NAME FROM LANTOP_REPORT_CONFIG_DETAILS T WHERE T.REPORT_CONFIG_ID = ? AND T.CONFIG_TYPE = ?";
        List<Map<String, Object>> list = null;
        list = jdbcAvicit.getJdbcTemplate().queryForList(sql, pid, configType);
        return list;
    }

    /**
     * 模板id查询报表配置
     * @param templateId
     * @return List<Map<String, Object>>
     */
    public List<Map<String, Object>> findLantopReportConfigByTemplateId(String templateId) {
        String sql = "SELECT T.CONFIG_TYPE,T.CONFIG_FIELD_NUM,T.CONFIG_FIELD_NAME,T.REPORT_COUNT_TYPE,T.REPORT_COUNT_SYMBOL FROM LANTOP_REPORT_CONFIG_DETAILS T\n" + "LEFT JOIN LANTOP_REPORT_CONFIGURATION T2 ON T.REPORT_CONFIG_ID = T2.ID WHERE T2.REPORT_TEMPLATE_ID = ? ";
        List<Map<String, Object>> list = null;
        list = jdbcAvicit.getJdbcTemplate().queryForList(sql, templateId);
        return list;
    }

    /**
     * TODO 根据模板ID保存存储应输出字段
     * @param sysId  系统ID
     * @param templateId  模板ID
     * @param outputFields 应输出字段
     * @throws
     */
    public void saveLantopReportField(String sysId, String templateId, String outputFields) {
        // 设置应输出字段信息
        String[] fields = outputFields.split(",");
        int index = 0;
        for (String field : fields) {
            LantopReportField lantopReportField = new LantopReportField();
            lantopReportField.setId(ComUtil.getId()); // 生成UUID
            lantopReportField.setFieldChinese(field);
            lantopReportField.setFieldSerial(new BigDecimal(index)); // 设置字段顺序
            lantopReportField.setSysId(sysId);
            lantopReportField.setReportId(templateId); // 设置报表模板ID
            lantopReportField.setOrgId(SessionHelper.getCurrentOrgId());
            lantopReportField.setDeptId(SessionHelper.getCurrentDeptId());
            lantopReportField.setSysApplicationId(SessionHelper.getApplicationId());
            PojoUtil.setSysProperties(lantopReportField, OpType.insert); // 设置公共属性
            index++;
            hibernateDao.save(lantopReportField);
            SysLogUtil.log(lantopReportField, null, OpType.insert, OpResult.success);
            ;
        }
    }

    /**
     * @author youyu
     * 根据组织ID获得组织信息
     * @param orgId
     * @return Map<String,Object>
     * */
    private Map<String,Object> getOrgInfoById(String orgId){
        String sql = "SELECT * FROM CBB_TEMPLET_V T WHERE  T.ID='"+orgId+"' ";
        List<Map<String, Object>> list = jdbcAvicit.getJdbcTemplate().queryForList(sql);
        if(list.size()>0){
            return list.get(0);
        }
        return null;
    }

}
